<template>
	<view>
		<u-popup :show="popupShow" :round="10" mode="bottom" :safeAreaInsetBottom="true" :closeable="true"
			@close="popupShow = false;">
			<view class="login-popup">
				<view class="title">授权登录</view>
				<view class="cell">
					<text class="label">头像</text>
					<!-- #ifdef MP-WEIXIN -->
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" plain="true">
						<image slot="right-icon" class="avatar" :src="avatarUrl" mode="widthFix"
							style="width: 80rpx; height: 80rpx;" />
					</button>
					<!-- #endif -->
					<!-- #ifdef MP-ALIPAY -->
					<image slot="right-icon" class="avatar" :src="avatarUrl" mode="widthFix"
						style="width: 120rpx; height: 120rpx;" />
					<!-- #endif -->
				</view>
				<view class="cell">
					<text class="label">昵称</text>
					<input type="nickname" style="width: 100%;" class="weui-input" placeholder="请输入昵称" v-model="name" />
				</view>
				<view class="cell">
					<text class="label">手机号</text>
					<view style="width: 250rpx;">
						<button v-if="!phoneNumber" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
							class="get-phone-button">获取手机号码</button>
						<view style="text-align: right;" v-else>
							{{phoneNumber}}
						</view>
					</view>
				</view>
				<view class="submit-but">
					<view class="but">
						<u-button shape="circle" @click="cancel()" text="取消"></u-button>
					</view>
					<view class="but">
						<u-button color="#7E7DF3" shape="circle" @click="submit()" text="保存"></u-button>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		name: "login-popup",
		data() {
			return {
				popupShow: false,
				baseUrl: this.$configPath.baseURL,
				baseAvatarUrl: '/image/common/member-header-image-default.svg',
				avatarUrl: this.$configPath.staticFileUrl + '/image/common/member-header-image-default.svg',
				name: '',
				phoneNumber: '',
				memberInfo: [],
				defaultHeadImgUrl: this.$configPath.staticFileUrl + '/image/common/member-header-image-default.svg',
        storageKeyEnum : this.$storageKeyEnum,
				fileUrl: '',
			};
		},
		methods: {
			getAuthCode() {
				my.getAuthCode({
					scopes: 'auth_user',
					success: res => {
						const authCode = res.authCode;
						let param = {
							authCode: res.authCode
						}
						this.$api('aliApplet.getUserInfoShare', param).then(res => {
							if (res.status == 0) {
								this.avatarUrl = res.data.avatarUrl;
								this.name = res.data.name;
							} else {
								getApp().err("获取会员信息不成功，请稍后再试");
							}
						})
					},
					fail: err => {
						var this_ = this;
						uni.showModal({
							title: '温馨提示',
							content: '取消授权，可能会使部分服务无法使用',
							confirmText: '重新授权',
							cancelText: '取消授权',
							success(res) {
								if (res.confirm) {
									this_.getAuthCode()
								} else {
									this_.cancel()
								}
							}
						});
					}
				});
			},
			getPhoneNumber(e) {
        // console.info("获取手机号",e);
				const accountInfo = uni.getAccountInfoSync();
				// #ifdef MP-WEIXIN
				if (e.detail.errMsg == "getPhoneNumber:fail:user deny" || e.detail.errMsg ==
					"getPhoneNumber:fail user deny") {
					uni.showModal({
						showCancel: false,
						title: '温馨提示',
						content: '取消授权，可能会使部分服务无法使用',
						confirmText: '我知道了',
					});
				} else if (e.detail.errMsg.startsWith("getPhoneNumber:fail Error:")) {
					uni.showModal({
						showCancel: false,
						title: '提示',
						content: e.detail.errMsg,
						confirmText: '确定',
					});
				} else {
					let param = {
                        channelType: 'WX',
                        code:e.detail.code,
						            appId: accountInfo.miniProgram.appId,
					}

					this.$api('member.getPhoneNumber', param).then(res => {
						if (res.status == 0) {
							this.phoneNumber = res.data.mobile;
						} else {
							getApp().err('获取手机号码失败：' + res.msg);
						}
					})
				}
				//#endif

				// #ifdef MP-ALIPAY
				if (e.detail.errorMessage == "用户取消授权") {
					uni.showModal({
						title: '温馨提示',
						content: '取消授权，可能会使部分服务无法使用',
						confirmText: '我知道了',
						showCancel: false,
						success(res) {}
					});
				} else {
					my.getPhoneNumber({
						success: (res) => {
							console.log("ali-res", res)
							let response = JSON.parse(res.response)
							let params = {
                                channelType: 'ALI',
								sign: response.sign,
								response: response.response,
								appId: accountInfo.miniProgram.appId,
							};
							this.$api('member.getPhoneNumber', params).then(res => {
								if (res.status == 0) {
									this.phoneNumber = res.data.mobile
								} else {
									getApp().err('获取手机号码失败：' + res.msg);
								}
							})
						},
						fail: (err) => {
							console.log('授权失败', err)
						}
					})
				}
				//#endif
			},
			cancel() {
				this.avatarUrl = this.$configPath.staticFileUrl + this.baseAvatarUrl;
				this.popupShow = false;
				this.name = "";
			},
			loginShow() {
				this.memberInfo = this.$helpers.getCache(this.storageKeyEnum.member_info);
				// #ifdef MP-WEIXIN
				this.popupShow = true;
				//#endif

				// #ifdef MP-ALIPAY
				this.popupShow = true;
				this.getAuthCode();
				//#endif
        this.findBasicInformationById();
      },
			onChooseAvatar(e) {
				this.avatarUrl = e.detail.avatarUrl
				this.fileUrl = e.detail.avatarUrl;
			},
      //获取用户基础信息
      findBasicInformationById(){
        this.$api('member.findBasicInformationById').then(res => {
          if (res.status == 0) {
              if (res.data){
                  if (res.data.nickName && res.data.nickName !== '微信用户' && res.data.nickName !== '支付宝用户'){
                      this.name=res.data.nickName;
                  }
                  if (res.data.headImgUrl && res.data.headImgUrl !== this.$configPath.staticFileUrl + '/image/common/member-header-image-default.svg'){
                      this.fileUrl=res.data.headImgUrl;
                  }
                  if (res.data.mobile){
                      this.phoneNumber=res.data.mobile;
                  }
              }
          }
        })
      },
			submit() {
				let params = {};

				if (this.avatarUrl == this.$configPath.staticFileUrl + this.baseAvatarUrl) {
					getApp().err('请上传头像');
					return;
				}

				let reg = /^\s*$/
				if (reg.test(this.name)) {
					getApp().err('昵称不能为空');
					return;
				} else {
					params.nickName = this.name
				}

				if (!this.phoneNumber) {
					getApp().err('请获取手机号');
					return;
				} else {
					params.mobile = this.phoneNumber
				}

				uni.showLoading({
					title: '保存中...'
				})

				// #ifdef MP-WEIXIN
				uni.uploadFile({
					url: this.baseUrl + '/api/upload/uploadImage',
					filePath: this.fileUrl,
					name: 'image',
					header: {
						Authorization: 'Bearer ' + this.$helpers.getCache(this.storageKeyEnum.token_cache)
					},
					success: (uploadFileRes) => {
						let res = JSON.parse(uploadFileRes.data)
						if (res.status == 0) {
							this.avatarUrl = this.$configPath.imageUrl + res.data.keyRes;
							params.headImgUrl = this.avatarUrl;
							this.updateMemberInfo(params);
						} else {
							this.$helpers.toast(uploadFileRes.msg);
						}
					},
					fail: (error) => {
						uni.hideLoading();
						this.$helpers.toast(error.errMsg);
					},
				})
				//#endif

				// #ifdef MP-ALIPAY
				params.headImgUrl = this.avatarUrl;
				this.updateMemberInfo(params);
				//#endif
			},

			updateMemberInfo(params) {
				this.$api('member.updateInfo', params).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						this.$helpers.toast("保存成功");
						this.$emit('completeMemberInfo');
						this.cancel();

						let memberInfo = this.$helpers.getCache(this.storageKeyEnum.member_info);

						memberInfo.nickName = params.nickName;
						memberInfo.headImgUrl = params.headImgUrl;
						memberInfo.mobile = params.mobile;

						this.$helpers.setCache(this.storageKeyEnum.member_info, memberInfo);

						//获取所有页面栈实例列表
						let pages = getCurrentPages();
						//当前页页面实例
						let nowPage = pages[pages.length - 1];
						if (
							nowPage.route.endsWith(
								"pages-activity/activity-detail/activity-detail") ||
							nowPage.route.endsWith(
								"pages-pay/purchase-package/purchase-package") ||
							nowPage.route.endsWith(
								"pages-pay/recharge-package/recharge-package") ||
							nowPage.route.endsWith("pages-activity/pay-order/pay-order")
						) {
							return;
						}

						setTimeout(() => {
							if (nowPage.route.endsWith(
									"pages/member/member-center/member-center")) {
								// console.log("login后onShow()")
								nowPage.onShow();
							} else if (nowPage.route.endsWith(
									"pages/work-wx/receive-bi/receive-bi")) {
								//领券页面 ,判断是否是新用户
								nowPage.$vm.loginReturn();
							} else {
								// console.log("login后onLoad()")
								// #ifdef MP-WEIXIN
								nowPage.onLoad();
								//#endif
								// #ifdef MP-ALIPAY
								nowPage.onReady();
								//#endif
							}
						}, 200);
					} else {
						this.$helpers.toast("保存失败！" + res.msg);
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.get-phone-button {
		border-radius: 200rpx;
		padding: 0 12rpx;
		background-color: #7E7DF3;
		font-size: 28rpx;
		height: 40px;
		line-height: 40px;
		color: #FFFFFF;
	}

	.login-popup {
		height: auto;
		padding: 50rpx 40rpx 20rpx;


		.title {
			height: 50rpx;
			text-align: center;
			font-size: 32rpx;
			margin-bottom: 10rpx;
		}

		.cell {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100rpx;
			padding-bottom: 10rpx;
			border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
			font-size: 34rpx;

			.label {
				width: 200rpx;
			}

			.avatar-wrapper {
				border: 0;
				margin: 0;
				padding: 0;
				width: 100%;
				height: 80rpx;
				text-align: right;

				.avatar {
					border-radius: 50%;
					width: 80rpx;
					height: 80rpx;
				}
			}

			input {
				min-height: 50rpx;
				text-align: right;
			}

		}

		.submit-but {
			display: flex;
			justify-content: space-around;
			margin-top: 80rpx;

			.but {
				width: 250rpx;
			}
		}

	}
</style>
